const dgram = require('dgram')
const sock = dgram.createSocket('udp4')
const { jspack } = require('jspack')

const MY_PORT = 10010 // A 自己监听的端口
const PEER_HOST = '127.0.0.1' // B 的地址
const PEER_PORT = 10011 // B 监听的端口

function genData() {
  // 起始符
  const header = Buffer.from([0xeb, 0x90])
  // 命令单元
  const cmd = Buffer.from([0x01, 0x03])
  // 命令标识：命令包
  const flag = Buffer.from([0xfe])
  // 数据单元长度：64 (0x0040)
  const len = Buffer.from([0x00, 0x40])
  // 数据单元内容（填充为 0x00）
  const data = Buffer.alloc(64, 0x03)

  // 拼接待校验部分 (从命令单元开始)
  const checkRegion = Buffer.concat([cmd, flag, len, data])

  // BCC 校验：异或全部字节
  const bcc = checkRegion.reduce((acc, val) => acc ^ val, 0)

  // 组合完整包
  const packet = Buffer.concat([header, checkRegion, Buffer.from([bcc])])

  return packet
}

function genData1() {
  // 起始符
  const header = Buffer.from([0xeb, 0x90])
  // 命令单元
  const cmd = Buffer.from([0x01, 0x04])
  // 命令标识：命令包
  const flag = Buffer.from([0xfe])
  // 数据单元长度：64 (0x0040)
  const len = Buffer.from([0x00, 0x40])
  // 数据单元内容（填充为 0x00）
  const data = Buffer.alloc(64, 0x01)

  // 拼接待校验部分 (从命令单元开始)
  const checkRegion = Buffer.concat([cmd, flag, len, data])

  // BCC 校验：异或全部字节
  const bcc = checkRegion.reduce((acc, val) => acc ^ val, 0)

  // 组合完整包
  const packet = Buffer.concat([header, checkRegion, Buffer.from([bcc])])

  return packet
}



sock.on('message', (msg, rinfo) => {
  console.log(`[A<-] ${rinfo.address}:${rinfo.port} -> ${JSON.stringify(msg)}`)
  const buf = Buffer.from(msg)
  sock.send(buf, rinfo.port, rinfo.address)
})

sock.on('error', (err) => {
  console.error('A socket error:', err)
  sock.close()
})

sock.bind(MY_PORT, () => {
  console.log(`A listening on ${MY_PORT}`)
  setInterval(() => {
    const packet = genData()
    sock.send(packet, PEER_PORT, PEER_HOST)

    const packet1 = genData1()
    sock.send(packet1, PEER_PORT, PEER_HOST)
  }, 1000 * 3)
})


// console.log('通信链路检测包:', packet.length, packet)
// console.log('十六进制:', packet.toString('hex').toUpperCase())

// const result = jspack.Unpack('>HHBH64sB', packet)
// console.log('result:', result);

// // 使用 jspack 一次性解析结构（注意：第5个64s会返回字符串）
// const [header1, cmd1, flag1, len1, dataStr, bcc1] = jspack.Unpack('>HHBH64sB', packet)

// console.log('raw unpack result:', { header1, cmd1, flag1, len1, bcc1 })
// console.log('dataStr.length:', dataStr.length)

// // ✅ 手动从原Buffer中提取 data 的真实字节段
// // 对应偏移：7 ~ 71（长度64）
// const dataBuf = packet.slice(7, packet.length-1)

// console.log('dataBuf length:', dataBuf.length)
// console.log('dataBuf (hex):', dataBuf.toString('hex').toUpperCase())

// const [header1, cmd1, identify1, length1, , bcc1] = jspack.Unpack('>HHBH64sB', packet)
// const data1 = packet.slice(7, packet.length-1)

// console.log('dataBuf length:', data1.length)
// console.log('dataBuf (hex):', data1.toString('hex').toUpperCase())
